package cn.wl.pchart.service.impl;

import cn.wl.pchart.dao.UserMapper;
import cn.wl.pchart.entity.Infos;
import cn.wl.pchart.entity.Like;
import cn.wl.pchart.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 用户服务实现
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public Integer verifyExist(String id) {
        return userMapper.verifyExist(id);
    }

    @Override
    public void register(String id, String password) {
        userMapper.register(id, password);
    }

    @Override
    public String login(String id) {
        return userMapper.login(id).getPassword();
    }

    @Override
    public void doLike(String id, String like) {
        userMapper.doLike(id, like);
    }

    @Override
    public boolean isLike(String id, String like) {
        if (userMapper.isLike(id, like) == 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean isFriend(String id, String like) {
        if (isLike(id, like) && isLike(like, id)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Like getLikeList(String id, boolean flag) {
        try {
            Like like = new Like();
            like.setId(id);
            like.setFlag(flag);
            like.setData(new ArrayList<Object>());
            List<String> list;
            if (flag) {
                // 关注列表
                list = userMapper.getLikeList(id);
            } else {
                // 粉丝列表
                list = userMapper.getIsLikedList(id);
            }
            for (String i : list) {
                JSONObject temp = new JSONObject();
                temp.put("id", i);
                temp.put("name", userMapper.getName(i));
                temp.put("image", userMapper.getImage(i));
                temp.put("isFriend", isFriend(id, i));
                like.getData().add(temp);
            }
            // System.out.println(like.getData().toString());
            return like;
        } catch (Exception e) {
            System.out.println("获取关注/粉丝列表时出现异常...");
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void cancelLike(String id, String like) {
        userMapper.cancelLike(id, like);
    }

    @Override
    public Infos getUserInfos(String id) {
        return userMapper.getUserInfos(id);
    }

    @Override
    public void setUserInfos(String id, String name, String sex, String age, String constellation, String address, String image) {
        userMapper.setUserInfos(id, name, sex, age, constellation, address, image);
    }
}
